<?php
/**
 * Library Of Shared Code (LOSC)
 *
 * LICENSE
 *
 * This source file is subject to the New BSD License that is bundled
 * with this package in the file LICENSE.txt.
 *
 * @category   LOSC Framework
 * @package    Exception
 * @subpackage HTTP
 * @copyright  Copyright (c) 2008 Robin Skoglund (http://robinsk.net/)
 * @license    http://creativecommons.org/licenses/BSD/  New BSD License
 */

/**
 * Exception used to indicate that an illegal request method was used
 *
 * @category   LOSC Framework
 * @package    Exception
 * @subpackage HTTP
 * @copyright  Copyright (c) 2008 Robin Skoglund (http://robinsk.net/)
 * @license    http://creativecommons.org/licenses/BSD/  New BSD License
 */
class Losc_Exception_Http_MethodNotAllowed extends Losc_Exception_Http
{
    const DEFAULT_MSG = 'Request method not allowed.';
    
    /**
     * Request methods
     *
     * @var array
     */
    protected $_methods = array(
        'HEAD', 'GET', 'POST', 'PUT', 'DELETE', 'TRACE', 'OPTIONS', 'CONNECT'
    );
    
    /**
     * Contains allowed request methods
     *
     * @var array
     */
    protected $_allowed;
    
    /**
     * Creates exception
     *
     * @param string $message        [optional] human-readable error message
     * @param mixed  $substitutions  [optional] scalar value or array of values
     *                               to use for substitutions in exception
     *                               message
     * @param array  $allow          [optional] an array of request methods to
     *                               allow, defaults to 'POST'
     */
    public function __construct($message = self::DEFAULT_MSG,
                                $subtitutions = null,
                                array $allow = array('POST'))
    {
        $this->setAllowed($allow);
        parent::__construct($message, $subtitutions, 405);
    }
    
    /**
     * Sets allowed request methods
     *
     * @param  array $allowed
     * @return void
     */
    public function setAllowed(array $allowed)
    {
        $this->_allowed = array();
        
        foreach ($allowed as $method) {
            $method = strtoupper($method);
            if (in_array($method, $this->_methods)) {
                $this->_allowed[] = $method;
            }
        }
    }
    
    /**
     * Returns allowed request methods
     *
     * @return array
     */
    public function getAllowed()
    {
        return $this->_allowed;
    }
}
